package com.irdstudio.apicenter.gateway.web.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;

import com.irdstudio.apicenter.gateway.comm.MaccsPacket;
import com.irdstudio.apicenter.gateway.web.MaccsException;
import com.irdstudio.apicenter.gateway.web.MaccsTradeDefineVo;
import com.irdstudio.apicenter.gateway.web.view.JsonView;
import com.irdstudio.apicenter.gateway.web.view.View;

@Controller
public class WxUploadController implements IController {
	/* 文本日志输出 */
	private static final Logger logger = LoggerFactory.getLogger(WxUploadController.class);
	
	@Override
	public View execute(MaccsTradeDefineVo tradeDefine, MaccsPacket inPacket,
			HttpServletRequest request, HttpServletResponse response)
			throws MaccsException {
		List<String>  strList = new ArrayList<String>(); //文件上传至服务器成功返回码
		MaccsPacket uvo = new MaccsPacket();
		try {
			strList = uploadFileAction(request, response);
			//目前仅支持单文件上传
			if(strList == null || strList.size()== 0){
				throw new Exception("上传文件失败：返回的fileNet的文档编号列表为[0]");
			}
			String str = strList.get(0);
			
			if(StringUtils.isEmpty(str)){
				throw new Exception("上传文件失败：返回的fileNet的文档列表第一条数据的文档编号为空");
			}
			uvo.addVariable("returnCode", "0");
			uvo.addVariable("returnMsg", "");
			uvo.addVariable("uploadID", str); //返回路径
		}  catch (Exception e) {
			logger.error("微信上传文件失败", e);
			uvo.addVariable("returnCode", "9");
			uvo.addVariable("returnMsg", e.getMessage());
		} 
		return new JsonView(request, response, uvo);
	}
	
	/**
	 * 上传文件处理
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	public List<String> uploadFileAction(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		response.setContentType("text/html;charset=GBK");
		request.setCharacterEncoding("GBK");
		List<String> strList = new ArrayList<String>(); // 存储上传至服务器成功后返回数据
		DiskFileItemFactory factory = new DiskFileItemFactory(); // 基于磁盘文件项目创建一个工厂对象
		ServletFileUpload upload = new ServletFileUpload(factory); // 创建一个新的文件上传对象
		// 解决上传文件名的中文乱码
		upload.setHeaderEncoding("UTF-8");
		List<FileItem> list = upload.parseRequest(request);
		for (FileItem item : list) {
			// 如果fileitem中封装的是上传文件
			if (!item.isFormField()) {
				//String str = FileNetUtil.uploadFile(item);
				//strList.add(str);
			}
		}
		return strList;
	}

}
